<?php

namespace app\models;

use yii\db\ActiveRecord;
use Yii;

class User extends ActiveRecord{
	public static function tableName(){
		return "{{%user}}";
	}

	public function rules(){
		return [
			 ['openId', 'required', 'message' => '', 'on' => ['insertNuPa','updateNuPa','updateState']],
			 ['number', 'required', 'message' => '', 'on' => ['insertNuPa','updateNuPa']],
			 ['password', 'required', 'message' => '', 'on' => ['insertNuPa','updateNuPa']],
		];
	}	

	public function getNuPaByOpenId($openId){
		$data = self::find()->select(['openId','number','password'])->where('openId = :openId and state = :state',[':openId'=>$openId,':state'=>'1'])->asArray()->one();
		return $data;
	}

	public function judgeByOpenId($openId){
		$data = self::find()->where('openId = :openId and state = :state',[':openId'=>$openId,':state'=>'1'])->asArray()->one();
		if($data){
			return true;
		}
		return false;
	}

	public function insertNuPa($data){
		$this->scenario = 'insertNuPa';
		if($this->load($data,'') && $this->validate()){
			if($this->save()){
				return true;
			}
			return false;
		}
		return false;
	}
	
	public function updateNuPa($data){
		$this->scenario = 'updateNuPa';
		if($this->load($data,'') && $this->validate()){
			return (bool)$this->updateAll(['number'=>$this->number,'password'=>$this->password],'openId = :openId and state = :state',[':openId'=>$this->openId,':state'=>'1']);
		}
		return false;
	}

	public function updateState($data){
		$this->scenario = 'updateState';
		if($this->load($data,'') && $this->validate()){
			return (bool)$this->updateAll(['state'=>'0'],'openId = :openId and state = :state',[':openId'=>$this->openId,':state'=>'1']);
		}
		return false;
	}
}
